package com.aichat.ai_chatbackend.controller;

import com.aichat.ai_chatbackend.model.dto.chat.ChatRequest;
import com.aichat.ai_chatbackend.service.impl.CompanionChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/companion")
@Tag(name = "智能陪伴助手", description = "智能陪伴对话相关接口")
@Slf4j
public class CompanionChatController {

    @Autowired
    private CompanionChatService companionChatService;

    @GetMapping("/health")
    @Operation(summary = "健康检查", description = "检查陪伴聊天服务状态")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> status = new HashMap<>();
        status.put("status", "ok");
        status.put("timestamp", LocalDateTime.now().toString());
        status.put("service", "companion-chat");
        status.put("aiServiceHealthy", companionChatService.isAiServiceHealthy());
        return ResponseEntity.ok(status);
    }

    @PostMapping("/chat")
    @Operation(summary = "发送消息给陪伴助手", description = "用户与AI陪伴助手进行对话")
    public ResponseEntity<SseEmitter> chat(
            @Valid @RequestBody ChatRequest request) {

            String userId =  request.getSessionId(); // 从认证信息获取用户ID
            log.info("用户 {} 发送消息: {}", request.getSessionId(), request.getUserMessage());
            SseEmitter emitter = new SseEmitter(60000L); // 60秒超时

            companionChatService.chatWithCompanionStream(userId, request,emitter);

            log.info("AI回复成功，用户: {}", userId);
            return ResponseEntity.ok(emitter);
            

    }

    @GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "流式聊天", description = "与AI陪伴助手进行流式对话")
    public SseEmitter chatStream(@RequestParam("sessionId") String sessionId,@RequestParam("userCurrentMessage") String userCurrentMessage) {
        
        SseEmitter emitter = new SseEmitter(60000L); // 60秒超时
        
        try {
            log.info("用户 {} 开始流式对话: {}", sessionId, userCurrentMessage);

            ChatRequest chatRequest = new ChatRequest();
            chatRequest.setSessionId(sessionId);
            chatRequest.setUserMessage(userCurrentMessage);

            
            // 异步处理流式响应
            companionChatService.chatWithCompanionStream(sessionId, chatRequest, emitter);
            
        } catch (Exception e) {
            log.error("流式对话处理失败: {}", e.getMessage(), e);
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("抱歉，我现在有点累了，请稍后再试试吧~"));
                emitter.complete();
            } catch (Exception sendException) {
                emitter.completeWithError(sendException);
            }
        }
        
        return emitter;
    }


} 